package com.matthew.spring.db.transaction;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class JdbcTransaction {
	public DataSource dataSource;
	public DataSource getDataSource() {
		return dataSource;
	}
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	public void save() throws SQLException{
		Connection con = null;
		PreparedStatement stmt = null;
		try {
			con = dataSource.getConnection();
			stmt = con.prepareStatement("insert into customer(name,address) values('transa7','shanghai')");
			stmt.executeUpdate();
			throw new SQLException();
		} catch (SQLException e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			
		} finally{
			try {
				con.close();
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
	}
	public void save2() throws SQLException{
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		DataSourceTransactionManager transactionManager = (DataSourceTransactionManager)context.getBean("transactionManager");
		TransactionStatus status = transactionManager.getTransaction(def);
		
		
		Connection con = null;
		PreparedStatement stmt = null;
		try {
			con = transactionManager.getDataSource().getConnection();//dataSource.getConnection();
			con.setAutoCommit(false);
			stmt = con.prepareStatement("insert into customer(name,address) values('transa9','shanghai')");
			stmt.executeUpdate();
			throw new SQLException();
		} catch (SQLException e) {
			transactionManager.rollback(status);
		} finally{
			
			try {
				con.close();
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
	}
}
